package com.xx.controller;

import com.xx.domain.SysLog;
import com.xx.domain.User;
import com.xx.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;

/**
 * @Author : 徐闯 ssm_admin
 * @Date : 2021-05-19 17:05:07
 * @Description : 用于获取系统日志信息的切面类
 **/
@Aspect
@Component
public class SystemLog {
    @Autowired
    private SysLogService sysLogService; //日志业务实例
    @Autowired
    private HttpServletRequest request; //请求对象
    private Date accessDate; //访问时间
    private Class executeClass;//执行所用时间

    @Before("execution(* com.xx.controller.*.*(..))")
    public void beforHandler(JoinPoint joinPoint){
        //获取时间
        accessDate = new Date();
        //获取执行的controller
        executeClass = joinPoint.getTarget().getClass();
    }
    @After("execution(* com.xx.controller.*.*(..))")
    public void afterHandler(JoinPoint joinPoint){
        if(executeClass != SystemLogController.class){
            //获取执行代码所用时间 单位(毫秒)
            long executeTime = new Date().getTime() - accessDate.getTime();
            //获取类名
            String className = executeClass.getName();
            //获取url
            String url = request.getRequestURI();
            //获取ip
            String ip = request.getRemoteAddr();
            //获取用户
            String username = request.getRemoteUser();
            // 将信息封装到SysLog实例中
            SysLog sysLog = new SysLog();
            sysLog.setIp(ip);
            sysLog.setUrl(url);
            sysLog.setUsername(username);
            sysLog.setExecuteTime(executeTime);
            sysLog.setClassName(className);
            sysLog.setAccessDate(accessDate.toLocaleString());
            System.out.println(sysLog);
            sysLogService.insertOne(sysLog);
        }/*else{
            System.out.println("..........");
        }*/
    }
}
